package com.yjhb.android.sbz.fragment;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.yjhb.android.sbz.R;
import com.yjhb.android.sbz.activity.BlacklistActivity;
import com.yjhb.android.sbz.activity.ContactUSActivity;
import com.yjhb.android.sbz.mvp.chat.ChatPresenter;
import com.yjhb.android.sbz.mvp.chat.ChatView;
import com.yjhb.android.sbz.tool.Tool;
import com.jojo.android.zxlib.base.BaseFragment;
import com.jojo.android.zxlib.tool.ZxActivityTool;
import com.jojo.android.zxlib.tool.ZxLogTool;
import com.jojo.android.zxlib.tool.ZxToast;
import com.tencent.imsdk.v2.V2TIMFriendInfo;
import com.tencent.imsdk.v2.V2TIMFriendOperationResult;
import com.tencent.imsdk.v2.V2TIMGroupAtInfo;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.qcloud.tim.uikit.component.TitleBarLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.ChatLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.input.InputLayout;
import com.tencent.qcloud.tim.uikit.modules.chat.layout.message.MessageLayout;
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfo;
import com.tencent.qcloud.tim.uikit.modules.group.info.StartGroupMemberSelectActivity;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfo;
import com.tencent.qcloud.tim.uikit.modules.message.MessageInfoUtil;
import com.tencent.qcloud.tim.uikit.utils.TUIKitConstants;
import com.tencent.qcloud.tim.uikit.utils.TUIKitLog;
import com.tencent.qcloud.tim.uikit.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

/**
 * 创建者 zx
 * 创建时间 2020/12/24 9:08
 */
public class ChatFragment extends BaseFragment<ChatPresenter> implements ChatView {
    private final String TAG = "ChatFragment";
    @BindView(R.id.chat_layout)
    ChatLayout mChatLayout;
    @BindView(R.id.customerService_tv)
    TextView customerService_tv;
    @BindView(R.id.title_tv)
    TextView title_tv;
    @BindView(R.id.title_right_tv)
    TextView title_right_tv;
    @BindView(R.id.tips_tv)
    TextView tips_tv;
    ChatInfo mChatInfo;
    int entrance; //入口 0消息界面，1任务详情，2任务审核,3联系客服,4举报维权,5进行中任务,6分享任务,7联系我们
    String extraData;
    /**
     * 是否在黑名单
     */
    boolean isBlackList = false;

    private TitleBarLayout mTitleBar;

    @Override
    protected ChatPresenter initPresenter() {
        return new ChatPresenter(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.chat_fragment;
    }

    @Override
    protected void initUI() {
        //单聊组件的默认UI和交互初始化
        mChatLayout.initDefault();
        mChatLayout.setChatInfo(mChatInfo);
        //如果是客服界面，则打开自动回复
        mChatLayout.setAutoReply(entrance == 3);
        //如果是任务详情界面进入，则开启自动发送任务链接
        if ((entrance == 1 || entrance == 6) && extraData != null) {
            mChatLayout.setSendTaskUri(extraData);
            if (entrance == 6) {
                mChatLayout.sendTaskInfo();
            }
        } else if (entrance == 7) {
            tips_tv.setVisibility(VISIBLE);
            mChatLayout.setAutoReply(false);
            mChatLayout.addWarningTips("人工客服在线时间：09:00-22:00");
            mChatLayout.addWarningTips("客服" + mChatInfo.getId() + "为您服务");
            mChatLayout.addReplyMsg("请详细描述您所遇到的问题，以便我们客服人员能够快速了解问题帮助您！\n" +
                    "\n" +
                    "【提供充分、详细的文字说明，并加上对应的截图/视频。一次性完整的描述您的问题。客服收到消息后，会尽快处理。】\n" +
                    "\n" +
                    "（发送在吗、你好等无效信息，客服一律不回复！）");
            mChatLayout.refresh();
        }
        mChatLayout.getInputLayout().disableSendFileAction(true);
        mChatLayout.getInputLayout().disableVideoRecordAction(false);
        //获取单聊面板的标题栏
        mTitleBar = mChatLayout.getTitleBar();
        mTitleBar.setLeftIcon(R.mipmap.back_w);
        mTitleBar.setVisibility(GONE);
        title_tv.setText(mChatInfo.getChatName());
        if (entrance == 3) {
            title_right_tv.setVisibility(GONE);
        }


        mChatLayout.getMessageLayout().setOnItemClickListener(new MessageLayout.OnItemClickListener() {
            @Override
            public void onMessageLongClick(View view, int position, MessageInfo messageInfo) {
                //因为adapter中第一条为加载条目，位置需减1
                mChatLayout.getMessageLayout().showItemPopMenu(position - 1, messageInfo, view);
            }

            @Override
            public void onItemClick(MessageInfo messageInfo) {
                try {
                    Map<String, String> map = MessageInfoUtil.resolveCustomMsg(messageInfo.getExtra().toString());
                    Tool.startEditTaskDetailActivity(getContext(), Integer.parseInt(map.get("id")));
                } catch (Exception e) {
                    ZxLogTool.err(e);
                }
            }

            @Override
            public void onUserIconClick(View view, int position, MessageInfo messageInfo) {
                if (null == messageInfo) {
                    return;
                }
                try {
                    if (!messageInfo.isSelf())
                        Tool.startUserInfoActivity(getContext(), Integer.parseInt(messageInfo.getFromUser()));
                } catch (Exception e) {
                }


            }

            @Override
            public void onCustomMsgClick(String text, MessageInfo messageInfo) {
                text = text.replace(text.substring(0, text.indexOf('.') + 1), "");
                mChatLayout.sendMessage(MessageInfoUtil.buildTextMessage(text), false);
            }
        });

        mChatLayout.getInputLayout().setStartActivityListener(new InputLayout.onStartActivityListener() {
            @Override
            public void onStartGroupMemberSelectActivity() {
                Intent intent = new Intent(getContext(), StartGroupMemberSelectActivity.class);
                GroupInfo groupInfo = new GroupInfo();
                groupInfo.setId(mChatInfo.getId());
                groupInfo.setChatName(mChatInfo.getChatName());
                intent.putExtra(TUIKitConstants.Group.GROUP_INFO, groupInfo);
                startActivityForResult(intent, 1);
            }

            @Override
            public boolean handleStartGroupLiveActivity() {
                // 打开群直播
//                LiveRoomAnchorActivity.start(DemoApplication.instance(), mChatInfo.getId());
                // demo层对消息进行处理，不走默认的逻辑
                return true;
            }
        });
        if (entrance != 3) {
            customerService_tv.setVisibility(GONE);
        }
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initData() {
        presenter.getProblems();
//        getBlackList();
    }

    @OnClick(R.id.customerService_tv)
    void onCustomerService() {
//        customerService_tv.setVisibility(GONE);
//        mChatLayout.setAutoReply(false);
//        mChatLayout.addWarningTips("客服在线时间：08:00-22:00");
//        mChatLayout.addWarningTips("客服" + mChatInfo.getId() + "为您服务");
//        mChatLayout.addReplyMsg("您好，请输入您要咨询的问题？");
//        mChatLayout.refresh();
        ZxActivityTool.skipActivity(getActivity(), ContactUSActivity.class);
    }

    @OnClick(R.id.back)
    void onBack(){
        getActivity().finish();
    }
    @OnClick(R.id.title_right_tv)
    void onRight(){
        Intent intent = new Intent(getContext(), BlacklistActivity.class);
        intent.putExtra("userId", mChatInfo.getId());
        startActivity(intent);
    }

    /**
     * 获取黑名单
     */
    private void getBlackList() {
        V2TIMManager.getFriendshipManager().getBlackList(new V2TIMValueCallback<List<V2TIMFriendInfo>>() {
            @Override
            public void onError(int code, String desc) {
                TUIKitLog.e(TAG, "getBlackList err code = " + code + ", desc = " + desc);
                ToastUtil.toastShortMessage("Error code = " + code + ", desc = " + desc);
            }

            @Override
            public void onSuccess(List<V2TIMFriendInfo> v2TIMFriendInfos) {
                if (v2TIMFriendInfos != null && v2TIMFriendInfos.size() > 0) {
                    for (V2TIMFriendInfo friendInfo : v2TIMFriendInfos) {
                        if (TextUtils.equals(friendInfo.getUserID(), mChatInfo.getId())) {
                            if (mChatLayout != null) {
                                mChatLayout.getTitleBar().getRightTitle().setText("移除黑名单");
                            }
                            isBlackList = true;
                            return;
                        }
                    }
                    isBlackList = false;
                    if (mChatLayout != null)
                        mChatLayout.getTitleBar().getRightTitle().setText("加入黑名单");
                } else {
                    isBlackList = false;
                    if (mChatLayout != null)
                        mChatLayout.getTitleBar().getRightTitle().setText("加入黑名单");
                }
            }
        });
    }

    /**
     * 加入黑名单
     */
    private void addBlack() {

        List<String> idList = new ArrayList<>();
        idList.add(mChatInfo.getId());
        V2TIMManager.getFriendshipManager().addToBlackList(idList, new V2TIMValueCallback<List<V2TIMFriendOperationResult>>() {
            @Override
            public void onError(int code, String desc) {
                TUIKitLog.e(TAG, "addBlackList err code = " + code + ", desc = " + desc);
                ToastUtil.toastShortMessage("失败了， 错误码：" + code + ", 描述：" + desc);
            }

            @Override
            public void onSuccess(List<V2TIMFriendOperationResult> v2TIMFriendOperationResults) {
                ZxToast.showSuccessBottomToast("已加入黑名单");
                getBlackList();
            }
        });
    }

    /**
     * 从黑名单移除
     */
    private void deleteBlack() {
        List<String> idList = new ArrayList<>();
        idList.add(mChatInfo.getId());
        V2TIMManager.getFriendshipManager().deleteFromBlackList(idList, new V2TIMValueCallback<List<V2TIMFriendOperationResult>>() {
            @Override
            public void onError(int code, String desc) {
                TUIKitLog.e(TAG, "deleteBlackList err code = " + code + ", desc = " + desc);
                ToastUtil.toastShortMessage("失败了， 错误码：" + code + ", 描述：" + desc);
            }

            @Override
            public void onSuccess(List<V2TIMFriendOperationResult> v2TIMFriendOperationResults) {
                ZxToast.showSuccessBottomToast("已从黑名单移除");
                getBlackList();
            }
        });
    }

    private void updateAtInfoLayout() {
        int atInfoType = getAtInfoType(mChatInfo.getAtInfoList());
        switch (atInfoType) {
            case V2TIMGroupAtInfo.TIM_AT_ME:
                mChatLayout.getAtInfoLayout().setVisibility(VISIBLE);
                mChatLayout.getAtInfoLayout().setText(getString(R.string.ui_at_me));
                break;
            case V2TIMGroupAtInfo.TIM_AT_ALL:
                mChatLayout.getAtInfoLayout().setVisibility(VISIBLE);
                mChatLayout.getAtInfoLayout().setText(getString(R.string.ui_at_all));
                break;
            case V2TIMGroupAtInfo.TIM_AT_ALL_AT_ME:
                mChatLayout.getAtInfoLayout().setVisibility(VISIBLE);
                mChatLayout.getAtInfoLayout().setText(getString(R.string.ui_at_all_me));
                break;
            default:
                mChatLayout.getAtInfoLayout().setVisibility(GONE);
                break;

        }
    }

    private int getAtInfoType(List<V2TIMGroupAtInfo> atInfoList) {
        int atInfoType = 0;
        boolean atMe = false;
        boolean atAll = false;

        if (atInfoList == null || atInfoList.isEmpty()) {
            return V2TIMGroupAtInfo.TIM_AT_UNKNOWN;
        }

        for (V2TIMGroupAtInfo atInfo : atInfoList) {
            if (atInfo.getAtType() == V2TIMGroupAtInfo.TIM_AT_ME) {
                atMe = true;
                continue;
            }
            if (atInfo.getAtType() == V2TIMGroupAtInfo.TIM_AT_ALL) {
                atAll = true;
                continue;
            }
            if (atInfo.getAtType() == V2TIMGroupAtInfo.TIM_AT_ALL_AT_ME) {
                atMe = true;
                atAll = true;
                continue;
            }
        }

        if (atAll && atMe) {
            atInfoType = V2TIMGroupAtInfo.TIM_AT_ALL_AT_ME;
        } else if (atAll) {
            atInfoType = V2TIMGroupAtInfo.TIM_AT_ALL;
        } else if (atMe) {
            atInfoType = V2TIMGroupAtInfo.TIM_AT_ME;
        } else {
            atInfoType = V2TIMGroupAtInfo.TIM_AT_UNKNOWN;
        }

        return atInfoType;

    }


    @Override
    public void onFailure(int code, String msg) {
        onCustomerService();
    }

    @Override
    public void onProblems(Map<String, String> problems) {
        StringBuilder stringBuilder = new StringBuilder("您可能关心以下常见问题：");
        int num = 0;
        for (String problem : problems.keySet()) {
            stringBuilder.append('\n');
            stringBuilder.append('{');
            stringBuilder.append(++num);
            stringBuilder.append(".");
            stringBuilder.append(problem);
            stringBuilder.append("}");
        }
        mChatLayout.setCustomMsg(stringBuilder.toString());
        mChatLayout.setProblems(problems);
        mChatLayout.addAutoReply();
        mChatLayout.refresh();
    }


    public void setChatInfo(ChatInfo chatInfo) {
        this.mChatInfo = chatInfo;
    }

    public void setEntrance(int entrance) {
        this.entrance = entrance;
    }

    public void setExtraData(String extraData) {
        this.extraData = extraData;
    }
}
